import React, { useEffect, useState } from 'react'
import UserStore from '../../store/UserStore';
import { BackHandler, Image, StyleSheet, Text, TextInput, ToastAndroid, TouchableOpacity, View } from 'react-native'
import { formatPhone, replaceBlank } from '../../utils/StringUtil';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import icon_exchange from '../../assets/icon_exchange.png';
import icon_eye_open from '../../assets/icon_eye_open.png';
import icon_eye_close from '../../assets/icon_eye_close.png';
import icon_triangle from '../../assets/icon_triangle.png';

export default function InputLogin(props: any) {
  const { changeLoginType, check } = props // 更改登录方式
  const [phone, setPhone] = useState<string>('187 5160 9896'); // 收集手机号
  const [pwd, setPwd] = useState<string>(''); // 收集密码
  const [eyeOpen, setEyeOpen] = useState<boolean>(false) // 密码遮盖
  const [canLogin, setCanLogin] = useState<boolean>(false) // 是否可以进行登录

  useEffect(() => {
    const backAction = () => {
      changeLoginType()
      return true // true 不关闭应用
    };
    // 监听返回键
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    );
    return () => backHandler.remove();
  }, []);
  useEffect(() => {
    if (phone.length === 13 && pwd.length === 6) {
      setCanLogin(true)
    } else {
      setCanLogin(false)
    }
  }, [phone, pwd])

  const navigation = useNavigation<StackNavigationProp<any>>()

  const onLogin = () => {
    if (!canLogin) {
      ToastAndroid.showWithGravity(
        "登录失败！请检查用户名和密码",
        ToastAndroid.SHORT,
        ToastAndroid.TOP
      );
      return
    }
    if (!check) {
      ToastAndroid.show('请先阅读协议', ToastAndroid.SHORT);
      return
    }

    UserStore.requestLogin(replaceBlank(phone), pwd, (success: boolean) => {
      if (success) {
        ToastAndroid.showWithGravity(
          "登录成功！",
          ToastAndroid.SHORT,
          ToastAndroid.TOP
        );
        navigation.replace('MainTab')
      } else {
        ToastAndroid.showWithGravity(
          "登录失败！请检查用户名和密码",
          ToastAndroid.SHORT,
          ToastAndroid.TOP
        );
      }
    })
  }



  return (
    <View style={styles.root}>
      <View style={[styles.titleLayout, styles.topLayout]} >
        <Text style={styles.titleTxt}> 密码登录 </Text>
      </View>
      <View style={styles.titleLayout} >
        <Text style={styles.tipTxt}> 未注册的手机号登录成功后会自动注册 </Text>
      </View>

      <View style={styles.phoneLayout}>
        <Text style={styles.pre86}>+86</Text>
        <Image style={styles.triangle} source={icon_triangle} />
        <TextInput
          style={styles.phoneInp}
          placeholderTextColor="#bbb"
          placeholder='请输入手机号码'
          autoFocus={false}
          keyboardType='number-pad'
          maxLength={13}
          value={phone}
          onChangeText={(text: string) => {
            setPhone(formatPhone(text));
          }}
        />
      </View>

      <View style={styles.phoneLayout}>
        <TextInput
          style={[styles.phoneInp, styles.pwdInp]}
          placeholderTextColor="#bbb"
          placeholder='输入密码'
          autoFocus={false}
          keyboardType='number-pad'
          maxLength={6}
          secureTextEntry={!eyeOpen} // 是否遮盖
          value={pwd}
          onChangeText={(text: string) => {
            setPwd(text);
          }}
        />
        <TouchableOpacity
          onPress={() => {
            setEyeOpen(!eyeOpen)
          }}
        >
          <Image
            style={styles.iconEye}
            source={eyeOpen ? icon_eye_open : icon_eye_close}
          />
        </TouchableOpacity>
      </View>

      <View style={styles.changeLayout}>
        <Image style={styles.exchangeIcon} source={icon_exchange} />
        <Text style={styles.codeLoginTxt}>验证码登陆</Text>
        <Text style={styles.forgetPwdTxt}>忘记密码？</Text>
      </View>

      <TouchableOpacity
        style={[styles.loginButton, canLogin ? styles.canLoginButton : styles.nocanLoginBtn]}
        activeOpacity={0.7}
        onPress={onLogin}
      >
        <Text style={[styles.loginBtnTxt, canLogin ? styles.canLoginTxt : styles.nocanLoginTxt]}>登录</Text>
      </TouchableOpacity>

    </View>
  )
}
const styles = StyleSheet.create({
  root: {
    width: '100%',
    height: '100%',
    flexDirection: 'column',
    alignItems: 'center',
    position: 'relative'
  },
  topLayout: {
    marginTop: 20
  },
  titleLayout: {
    marginVertical: 6
  },
  titleTxt: {
    fontSize: 24,
    fontWeight: '500',
    textAlign: 'center',
    color: '#333'
  },
  tipTxt: {
    fontSize: 12,
    color: '#ccc'
  },
  pre86: {
    fontSize: 18,
    color: '#ccc'
  },
  triangle: {
    width: 12,
    height: 6,
    marginLeft: 6,
  },
  phoneLayout: {
    flexDirection: 'row',
    alignItems: 'center',
    width: '75%',
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
    marginVertical: 10
  },
  phoneInp: {
    paddingLeft: 12,
    fontSize: 18,
    color: '#333'
  },
  pwdInp: {
    width: '90%',
    fontSize: 16
  },
  iconEye: {
    width: 20,
    height: 20
  },
  changeLayout: {
    width: '75%',
    marginTop: 15,
    alignItems: 'center',
    justifyContent: 'space-around',
    flexDirection: 'row',
  },
  exchangeIcon: {
    width: 16,
    height: 16,
  },
  codeLoginTxt: {
    fontSize: 14,
    color: '#303080',
    flex: 1,
    marginLeft: 4,
  },
  forgetPwdTxt: {
    fontSize: 14,
    color: '#303080',
  },
  loginButton: {
    width: '75%',
    height: 56,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 28,
    marginTop: 28,
  },
  canLoginButton: {
    backgroundColor: '#ff2442',
  },
  nocanLoginBtn: {
    backgroundColor: '#999',
  },
  loginBtnTxt: {
    lineHeight: 56,
    textAlign: 'center',
    fontSize: 18,
  },
  canLoginTxt: {
    color: '#fff'
  },
  nocanLoginTxt: {
    color: '#f1f1f1'
  }
})